/**  
 * @Title: FlowService.java
 * @Description: TODO(描述)
 * @author liuyi
 * @date 2023-03-23 15:09:58 
 */
package com.fsxgt.datagrid.console.service.impl;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.fsxgt.datagrid.console.exception.RunningException;
import com.fsxgt.datagrid.core.utils.ReturnT;

import lombok.extern.slf4j.Slf4j;


@Slf4j
@Service
public class ServerService {

	@Autowired
	private RestTemplate restTemplate;
	
	private static final Logger logger = LoggerFactory.getLogger(ServerService.class);
	
	private final AtomicInteger index = new AtomicInteger(1);
	
	public  Set<String> executors = new HashSet();
	
	
	public synchronized String getServer() throws RunningException {
		
		if(executors.size()==0) {
			throw new RunningException("没有可用执行器");
		}
		return (String) executors.toArray()[index.getAndIncrement()%executors.size()];
	}
	
	public synchronized void register(String remote, int port) {
		String address=remote+":"+port;
		executors.add(address);
	}
	
	public synchronized Set<String> getServerList() {
		return executors;
		
	}
	@Scheduled(cron = "0/10 * * * * ? ")
	public void clear() {
		
		executors.forEach((address)->{
			try {
				
		        Map result=httpPost("http://"+address+"/server/test",new HashMap(), Map.class);
		        
		        if(!(result!=null&&result.get("code").equals(ReturnT.SUCCESS_CODE))) {
		        	synchronized(this) {
		        		executors.remove(address);
		        	}
		        }
			}catch(Exception e) {
				logger.error("",e);
				synchronized(this) {
	        		executors.remove(address);
	        	}
			}
		});
	}
	

	
	public <T> T httpPost(String url,Map params,Class<T> responseType) {
		HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=UTF-8");
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<HashMap<String, Object>> httpEntity = new HttpEntity(params, headers);
        return restTemplate.postForObject(url, httpEntity, responseType);
	}
	
	
	
	

}
